<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="120px">
    <el-row>
      <el-col :span="12">
        <el-form-item label="客户代码" prop="customerCode">
          <el-input v-model="form.customerCode" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item
          label="客诉反馈日期"
          prop="customerComplaintFeedbackTime"
        >
          <el-date-picker
            v-model="form.customerComplaintFeedbackTime"
            type="date"
            placeholder="年/月/日"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd"
          ></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客诉问题描述" prop="problemDescription">
          <el-input
            v-model="form.problemDescription"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="问题确定" prop="problemIdentification">
          <el-input
            v-model="form.problemIdentification"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="问题性质" prop="problemNature">
          <el-input
            v-model="form.problemNature"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="问题分析" prop="problemAnalysis">
          <el-input
            v-model="form.problemAnalysis"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="CAPA纠正预防措施" prop="correctiveActions">
          <el-input
            v-model="form.correctiveActions"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="不良图片" prop="defectivePhotoArray" class="">
          <el-upload
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            class="avatar-uploader"
            action="/admin/sys-file/upload"
          >
            <div class="avatar-image">
              <div class="image-container" v-for="(photo, index) in form.defectivePhotoArray" :key="index">
                <img :src="photo" class="avatar" @click.stop=""/>
                <span class="delete-icon" @click.stop="removeDefectivePhoto(index)">
                <b style="color: red">删除</b>
              </span>
              </div>
              <i class="el-icon-plus avatar-uploader-icon"/>
            </div>

          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="报告附件" prop="reportAttachment">
          <el-upload
            :headers="headers"
            :show-file-list="false"
            :on-success="handlereportAttachmentSuccess"
            class="avatar-uploader"
            action="/admin/sys-file/upload"
          >
            <!-- 新增文件信息回显区域 -->
            <div v-if="form.reportAttachment" style="margin-left: 8px;">
              {{ form.reportAttachmentName }} <br>
              <span class="delete-icon" @click.stop="removeDefectivePhoto">
                <b style="color: red;margin-right: 10px;" @click.stop="removeAttachment(1)">删除</b>
                <b style="color: #409eff" @click.stop="downloadFile(form.reportAttachment)">下载</b>
              </span>
            </div>
            <el-button v-else size="small" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="附件超链接" prop="attachmentLink">
          <el-upload
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAttachmentLinkSuccess"
            class="avatar-uploader"
            action="/admin/sys-file/upload"
          >

            <!-- 新增文件信息回显区域 -->
            <div v-if="form.hyperlinkAttachment" style="margin-left: 8px;">
              {{ form.hyperlinkAttachmentName }} <br>
              <span class="delete-icon" @click.stop="removeDefectivePhoto">
                <b style="color: red;margin-right: 10px;" @click.stop="removeAttachment(2)">删除</b>
                <b style="color: #409eff" @click.stop="downloadFile(form.hyperlinkAttachment)">下载</b>
              </span>
            </div>
            <el-button v-else size="small" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="form.handler" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="结案日期" prop="caseClosureDate">
          <el-date-picker
            v-model="form.caseClosureDate"
            type="date"
            placeholder="年/月/日"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd"
          ></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="责任部门" prop="responsibleDepartment">
          <el-input
            v-model="form.responsibleDepartment"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="效果验证" prop="effectivenessVerification">
          <el-input
            v-model="form.effectivenessVerification"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="品质主管确认" prop="qualitySupervisorConfirmation">
          <el-input
            v-model="form.qualitySupervisorConfirmation"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <div style="text-align: center">
      <el-button type="primary" @click="submitForm('form')">提交</el-button>
      <el-button @click="resetForm('form')">取消</el-button>
    </div>
  </el-form>
</template>

<script>
import {
  getObj,
  putObj,
  addObj,
} from "@/api/customercomplaintrecordledgercopy";
import store from "@/store";
import { uploadFile, } from "@/api/pfoc/filelibrary";
import { download,fetchList as  fetchFileList} from "@/api/admin/sys-file";

export default {
  data() {
    return {
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      form: {
        customerCode: "",
        productName: "",
        customerComplaintFeedbackTime: "",
        problemDescription: "",
        problemIdentification: "",
        problemNature: "",
        problemAnalysis: "",
        correctiveActions: "",
        defectivePhotoArray: [],
        reportAttachment: "",
        attachmentLink: "",
        handler: "",
        caseClosureDate: "",
        responsibleDepartment: "",
        effectivenessVerification: "",
        qualitySupervisorConfirmation: "",
        hyperlinkAttachment: "",
        hyperlinkAttachmentName: "",
        reportAttachmentName: ""
      },
      rules: {
        customerCode: [
          { required: true, message: "请输入客户代码", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
        ],
        customerComplaintFeedbackTime: [
          { required: true, message: "请选择客诉反馈日期", trigger: "change" },
        ],
        problemDescription: [
          { required: true, message: "请输入客诉问题描述", trigger: "blur" },
        ],
        // problemIdentification: [
        //   { required: true, message: "请输入问题确定", trigger: "blur" },
        // ],
        // problemNature: [
        //   { required: true, message: "请输入问题性质", trigger: "blur" },
        // ],
        // problemAnalysis: [
        //   { required: true, message: "请输入问题分析", trigger: "blur" },
        // ],
        // correctiveActions: [
        //   {
        //     required: true,
        //     message: "请输入CAPA纠正预防措施",
        //     trigger: "blur",
        //   },
        // ],
        // defectivePhotoArray: [{ required: true, message: "请上传不良图片", trigger: "change" }],
        // reportAttachment: [{ required: true, message: "请上传报告附件", trigger: "change" }],
        // handler: [{ required: true, message: "请输入处理人", trigger: "blur" }],
        // caseClosureDate: [
        //   { required: true, message: "请选择结案日期", trigger: "change" },
        // ],
        // responsibleDepartment: [
        //   { required: true, message: "请输入责任部门", trigger: "blur" },
        // ],
        // effectivenessVerification: [
        //   { required: true, message: "请输入效果验证", trigger: "blur" },
        // ],
        // qualitySupervisorConfirmation: [
        //   { required: true, message: "请输入品质主管确认", trigger: "blur" },
        // ],
      },

      loading: false,
      fileList: [],
    };
  },
  props: {
    ksId: {
      type: String,
    },
    dialogVisible: {
      type: Boolean,
    },
  },
  computed: {
    getImageFiles() {
      return this.fileList.filter((file) => this.isImage(file.name));
    },
    getOtherFiles() {
      return this.fileList.filter((file) => !this.isImage(file.name));
    },
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val && this.ksId) {
          // this.$refs[formName].resetFields();
          this.getDetail();
        } else {
          this.form = {
            customerCode: "",
            productName: "",
            customerComplaintFeedbackTime: "",
            problemDescription: "",
            problemIdentification: "",
            problemNature: "",
            problemAnalysis: "",
            correctiveActions: "",
            defectivePhotoArray: [],
            reportAttachment: "",
            reportAttachmentName: "",
            attachmentLink: "",
            handler: "",
            caseClosureDate: "",
            responsibleDepartment: "",
            effectivenessVerification: "",
            qualitySupervisorConfirmation: "",
            hyperlinkAttachment: "",
            hyperlinkAttachmentName: "",
          };
        }
      },
      immediate: true,
    },
    fileList: [],
    upUrl: "http://192.168.8.200:8078",
  },
  methods: {
    downloadFile(path) {
      download(path).then(async(res) => {
        console.log(res.request.responseURL);
        const link = document.createElement("a");
        link.href = res.request.responseURL;
        //   "http://192.168.8.200:8078/admin/sys-file/local/ce38d7d0a8c64bfda73e4de5e9c006ff.xlsx";
        // link.href = `http://192.168.8.200:8078${path}`
        link.download = await this.getFileName(path) // 设置下载的文件名
        link.click()
      })
    },
    async getFileName(p) {
      if (!p) return ''; // 处理空值
      const fileName = p.substring(p.lastIndexOf('/') + 1);
      try {
        const result = await fetchFileList({ currentPage: 1, pageSize: 1, fileName });
        if (result.status === 200 && result.data.code === 0 && result.data.data.records.length > 0) {
          return result.data.data.records[0].original; // 返回原始文件名
        } else {
          return fileName; // fallback：使用路径中的文件名
        }
      } catch (error) {
        console.error('获取文件信息失败:', error);
        return fileName; // 出错时返回路径中的文件名
      }
    },
    isImage(filename) {
      const imageExtensions = [
        "jpg",
        "jpeg",
        "png",
        "gif",
        "bmp",
        "tiff",
        "webp",
      ];
      const ext = filename.split(".").pop().toLowerCase();
      return imageExtensions.includes(ext);
    },
    previewFile(file) {
      if (
        typeof URL !== "undefined" &&
        typeof URL.createObjectURL === "function"
      ) {
        const url = URL.createObjectURL(file.raw);
        window.open(url, "_blank");
      } else {
        this.$message.error("当前浏览器不支持文件预览功能，请使用现代浏览器。");
      }
    },
    removeFile(file) {
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
    },
    generateObjectURL(file) {
      if (
        typeof URL !== "undefined" &&
        typeof URL.createObjectURL === "function"
      ) {
        return URL.createObjectURL(file);
      }
      return "";
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleAvatarSuccess(res, file) {
      if(!this.form.defectivePhotoArray){
        this.form.defectivePhotoArray =[]
      }
      this.form.defectivePhotoArray.push(res.data.url);
    },//form.defectivePhotoArray
    async handleAttachmentLinkSuccess(res, file) {
      this.form.hyperlinkAttachment = res.data.url;
      this.form.hyperlinkAttachmentName = await this.getFileName(res.data.url.substring(res.data.url.lastIndexOf('/') + 1));
    },
    async handlereportAttachmentSuccess(res) {
      this.form.reportAttachment = res.data.url;
      this.form.reportAttachmentName = await this.getFileName(res.data.url.substring(res.data.url.lastIndexOf('/') + 1));
    },
    removeDefectivePhoto(idnex1) {
      this.$confirm('确定删除这张图片吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.form.defectivePhotoArray.splice(idnex1, 1);
        this.$message.success('图片已删除');
      }).catch(() => {
        // 取消删除
      });
    },
    removeAttachment(val){
      this.$confirm('确定删除这个附件吗？', '提示', {
        type: 'warning'
      }).then(() => {
        if (val == 1) {
          this.form.reportAttachment = '';
          this.form.reportAttachmentName = '';
        } else if (val == 2) {
          this.form.hyperlinkAttachment = '';
          this.form.hyperlinkAttachmentName = '';
        }
        this.$message.success('附件已删除');
      }).catch(() => {
        // 取消删除
      });
    },
   async  getDetail() {
     const res =await getObj(this.ksId);
        this.form.customerCode = res.data.data.customerCode;
        this.form.productName = res.data.data.productName;
        this.form.customerComplaintFeedbackTime =
          res.data.data.customerComplaintFeedbackTime;
        this.form.problemDescription = res.data.data.problemDescription;
        this.form.problemNature = res.data.data.problemNature;
        this.form.problemAnalysis = res.data.data.problemAnalysis;
        this.form.correctiveActions = res.data.data.correctiveActions;
        this.form.defectivePhotoArray = res.data.data.defectivePhotoArray;
        this.form.problemIdentification = res.data.data.problemIdentification;
        this.form.handler = res.data.data.handler;
        this.form.qualitySupervisorConfirmation =
          res.data.data.qualitySupervisorConfirmation;
        this.form.reportAttachment = res.data.data.reportAttachment;
        this.form.attachmentLink = res.data.data.attachmentLink;
        this.form.caseClosureDate = res.data.data.caseClosureDate;
        this.form.responsibleDepartment = res.data.data.responsibleDepartment;

        this.form.effectivenessVerification =
          res.data.data.effectivenessVerification;
        this.form.hyperlinkAttachment = res.data.data.hyperlinkAttachment;
      if (this.form.hyperlinkAttachment) {
        this.form.hyperlinkAttachmentName = await this.getFileName(this.form.hyperlinkAttachment);
      }
      if (this.form.reportAttachment) {
        this.form.reportAttachmentName = await this.getFileName(this.form.reportAttachment);
      }
      console.log("=====",this.form)
    },
    submitForm(formName) {
      if(!this.form.defectivePhotoArray){
          this.form.defectivePhotoArray =[]
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.save();
        } else {
          this.$message.error("请填写必填项！");
          return false;
        }
      });
    },
    save() {
      if (this.ksId) {
        putObj({ ...this.form, id: this.ksId }).then((res) => {
          if (res) {
            this.$emit("success");
          }
        });
      } else {
        addObj({ ...this.form }).then((res) => {
          if (res) {
            this.$emit("success");
          }
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit("close");
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 15px;
}
.el-form-item {
  margin-bottom: 15px;
}
.avatar-image{
  display: flex;
  flex-wrap: wrap;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
  margin-right: 5px;
}
.avatar-uploader-icon{
  width: 80px !important;
  height: 80px !important;
  display: block;
  line-height: 80px !important;
  border: 1px solid #333;
}

</style>
